/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
export var largestValues = function (root) {
  const queue = [root]
  const ans = []
  while (queue.length) {
    const sz = queue.length
    let maxValue = -Infinity
    for (let i = 0; i < sz; i++) {
      const node = queue.shift()
      if (!node) continue
      maxValue = Math.max(maxValue, node.val)
      queue.push(node.left, node.right)
    }
    if (maxValue !== -Infinity) ans.push(maxValue)
  }
  return ans
}
